package br.unisinos.pdm;



import br.unisinos.pdm.bluetooth.BluetoothConnection;
import br.unisinos.pdm.bluetooth.GameClient;
import br.unisinos.pdm.bluetooth.GameServer;
import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
 * Ping Pong Bluetooth
 *
 * @author  Daniel Correa
 * @version 1.0
 */
public class GameMidlet extends MIDlet implements CommandListener, DiscoveryListener {

    private GameCanvas gameCanvas;
    private Display d;
    private Thread t;

    //Indentificador da aplicacao
    public static final String UUID = "0000000000000000000000AF2004BCEF";

    //Representa o dispositivo Bluetooth Local
    private LocalDevice localDevice;

    //Responsavel por realizar as buscas por dispositivos
    private DiscoveryAgent agent;

    //Lista de dispositivos encontrados
    private Vector devices = new Vector();

    private BluetoothConnection btConnection;

    private UUID[] uuidset = new UUID[]{new UUID(UUID, false)};

    private ServiceRecord record;

    private static final String[] elements = { "Iniciar Servidor", "Iniciar Cliente" };

    private final List menu = new List("Bluetooth Demo", List.IMPLICIT, elements, null);

    private final Command EXIT_CMD = new Command("Exit", Command.EXIT, 2);

    private final Command OK_CMD = new Command("Ok", Command.SCREEN, 1);

    public void startApp() {

        menu.addCommand(EXIT_CMD);
        menu.addCommand(OK_CMD);
        menu.setCommandListener(this);
        Display.getDisplay(this).setCurrent(menu);

        try{
            localDevice = LocalDevice.getLocalDevice();
            agent = localDevice.getDiscoveryAgent();
            searchDevices();
            
        }catch(BluetoothStateException ex){
            ex.printStackTrace();
        }
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable d) {

        if (c == EXIT_CMD) {
            destroyApp(true);
            notifyDestroyed();

            return;
        }

        switch (menu.getSelectedIndex()) {
        case 0: //SERVIDOR
            this.gameCanvas = new GameCanvas(true);
            this.t = new Thread(gameCanvas);
            t.start();
            Display.getDisplay(this).setCurrent(gameCanvas);

            //abri servidor
            btConnection = new GameServer(gameCanvas);
            btConnection.accept();

            break;

        case 1: //CLIENTE
            this.gameCanvas = new GameCanvas(false);
            this.t = new Thread(gameCanvas);
            t.start();
            Display.getDisplay(this).setCurrent(gameCanvas);
            try {
                agent.startInquiry(DiscoveryAgent.GIAC, this);
            } catch (BluetoothStateException ex) {
                ex.printStackTrace();
            }
            searchServices();
            break;

        default:
            System.err.println("Opção invalida...");

            break;
        }
    }

    public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass) {
        if(!devices.contains(remoteDevice)){
            devices.addElement(remoteDevice);
        }
    }

    public void inquiryCompleted(int discType) {

    }

    public void servicesDiscovered(int transID, ServiceRecord[] serviceRecord) {
        record = serviceRecord[0];
    }

    public void serviceSearchCompleted(int transID, int respCode) {
        
        btConnection = new GameClient(gameCanvas,record);
        btConnection.connect();
    }


    /**
     * Search for bluetooth devices.
     *
     * @return false if should end the component work.
     */
    private boolean searchDevices() {

        try {
            agent.startInquiry(DiscoveryAgent.GIAC, this);
        } catch (BluetoothStateException e) {
            System.err.println("Can't start inquiry now: " + e);
            return true;
        }

        return true;
    }

    /**
     * Search for proper service.
     *
     * @return false if should end the component work.
     */
    private boolean searchServices() {

        for (int i = 0; i < devices.size(); i++) {
            RemoteDevice rd = (RemoteDevice)devices.elementAt(i);

            try {
                agent.searchServices(null, uuidset, rd, this);
            } catch (BluetoothStateException e) {
                System.err.println("Can't search services for: " + rd.getBluetoothAddress() +
                    " due to " + e);
               continue;
            }
        }


        return true;
    }
}